
def lazy_range(up_to):
    index = 0
    while index < up_to:
        yield index
        index += 1


def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1


for i in fib(10):
    print(i)


lst = list(range(10))
lst2 = filter(lambda n: n > 3, lst)
print(list(lst2))

def my_filter(lst, minval): 
    return filter(lambda n: n > minval, lst)

lst3 = my_filter(lst, 3)
print(list(lst3))

lst4 = range(5)
import collections
print(lst4 is collections.Iterator)


a = range(1000) 
b = range(100)

import itertools
c = itertools.zip_longest(a,b)
print(list(c))


d = itertools.count(10, 2)
# for i in d:
#     print(d)

def genequars(N):
    idx = 2
    for i in range(N):
        new_idx = yield i**idx
        if new_idx != None:
            idx = new_idx

for item in genequars(10):
    print(item)

test_next = genequars(10)
print(test_next.send(None))
print(next(test_next))
print(test_next.send(None))
print(test_next.send(5))

print(sum(x for x in range(100000)))

def index_words(text):
    result = []
    if text:
        result.append(0)
    for index, letter in enumerate(text, 1):
        if letter == ' ':
            result.append(index)
    return result

def index_words2(text):
    if text:
        yield 0
    for index, letter in enumerate(text, 1):
        if letter == ' ':
            yield index

print(index_words('hello world renix hi hi '))


def simple_coroutine():
    print('-> coroutine started')
    x = yield
    print('-> coroutine received',x)


from functools import wraps


def coroutine(func):
    @wraps(func)
    def primer(*args, **kw):
        gen = func(*args, **kw)
        next(gen)
        return gen
    return primer

@coroutine
def averager(): 
    total = 0.0 
    count = 0 
    average = None 
    while True: 
        term = yield average
        if term == None:
            break
        total += term 
        count += 1 
        average = total/count
    return average

new_ave = averager()
print(new_ave.send(10))
print(new_ave.send(30))
try:
    new_ave.send(None)
except StopIteration as ex:
    print('average is',ex.value)

class DemoException(Exception): 
    """为这次演示定义的异常类型。""" 

def demo_exc_handling(): 
    print('-> coroutine started') 
    while True: 
        try: 
            x = yield
        except DemoException: 
            print('*** DemoException handled. Continuing...') 
        else: 
            print('-> coroutine received: {!r}'.format(x)) 
    raise RuntimeError('This line should never run.') 

from inspect import getgeneratorstate

exc_cor = demo_exc_handling()
next(exc_cor)
exc_cor.send(40)
exc_cor.close()
print(getgeneratorstate(exc_cor))